import { FrameworkConfig } from "./builder/framework-config";

const FS = require('fs');
const Path = require('path');
const { exec } = require('child_process');

/**
 * 扩展路径
 */
export const EXTENSION_PATH = Path.join(__dirname, '..');

/**
 * 执行命令
 * @param command 
 * @param cwd 
 */
export function exeCommand(command:string, cwd:string){
	return new Promise<{ error?:string, stdout?:string, stderr?:string }>((resolve)=>{
		return exec(command, { cwd : cwd }, (error, stdout, stderr) => {
			resolve({
				error : error,
				stdout : stdout,
				stderr : stderr,
			});
		});
	});
}

/**
 * 资源库函数
 */
export class AssetDB {
	/**
	 * 导入资源
	 * @param source 
	 * @param target 
	 * @param option 
	 */
	public static importAsset(source:string, target:string, option:{overwrite?:boolean, rename?:boolean} = {}) {
		return Editor.Message.send("asset-db", "import-asset", source, target, option);
	}
}

/**
 * 查找文件类型
 */
export enum FindFileType {
	FILE = 1,
	DIRECTORY = 2,
}

/**
 * 在指定目录中查找文件
 * @param dir 
 * @param filename 
 */
export function findFile(dir:string, filename:string, types:number = FindFileType.FILE | FindFileType.DIRECTORY){
	for(let file of FS.readdirSync(dir)){
		let npath = Path.join(dir, file);
		var info = FS.statSync(npath);
		if((file == filename) && (info.isDirectory() ? types & FindFileType.DIRECTORY : types & FindFileType.FILE)){
			return npath;
		}else if(info.isDirectory()){
			let result = findFile(npath, filename, types);
			if(result){
				return result;
			}
		}
	}
}

/**
 * 遍历目录路径
 */
export function mapDirectory(path_:string, callback:(Path:string, file:string, isdir:boolean)=>boolean) {
	for(let file of FS.readdirSync(path_)){
		let npath = Path.join(path_, file);
		var info = FS.statSync(npath);
		if(callback(npath, file, info.isDirectory())){
			return true;
		}else if(info.isDirectory()){
			if(mapDirectory(npath, callback)){
				return true;
			}
		}
	}
}

/**
 * 复制文件
 * @param srcPath 
 * @param destPath 
 */
export function copyFile(srcPath:string, destPath:string){
	FS.writeFileSync(destPath, FS.readFileSync(srcPath));
}

/**
 * 复制目录
 * @param src 
 * @param dest 
 */
export function copyDirectory(srcPath:string, destPath:string){
    if(FS.existsSync(srcPath)){
        if(!FS.existsSync(destPath)){
            FS.mkdirSync(destPath, { recursive : true });
        }
        for(let file of FS.readdirSync(srcPath)){
            let spath = Path.join(srcPath, file);
            let dpath = Path.join(destPath, file);
            var info = FS.statSync(spath);
            if(info.isDirectory()){
                copyDirectory(spath, dpath);
            }else{
                copyFile(spath, dpath);
            }
        }
    }
}

/**
 * 获得框架配置
 */
const modulesFile = Path.join(EXTENSION_PATH, 'framework', 'config.json');
let frameworkConfig:FrameworkConfig = null;
export function getFrameworkConfig(){
    if(!frameworkConfig){
        if(FS.existsSync(modulesFile)){
            frameworkConfig = JSON.parse(FS.readFileSync(modulesFile, { encoding : 'utf-8' }));
        }
    }
    return frameworkConfig;
}

/**
 * 获得扩展配置
 */
const packageFile = Path.join(EXTENSION_PATH, 'package.json');
let extensionConfig = null;
export function getExtensionConfig(){
    if(!extensionConfig){
        if(FS.existsSync(packageFile)){
            extensionConfig = JSON.parse(FS.readFileSync(packageFile, { encoding : 'utf-8' }));
        }
    }
    return extensionConfig;
}

/**
 * 确认字符串指定结尾
 * @param str 
 * @param target 
 */
export function confirmEnding(str:string, target:string) {
	return str.substring(str.length - target.length) == target;
}

/**
 * 获得所有游戏包
 */
export function getGamePacks(){
    let packs = [ "main" ];
	let packpath = Path.join(Editor.Project.path, 'assets', 'packs');
	if(FS.existsSync(packpath)){
		for(let p of FS.readdirSync(packpath)){
			let fstate = FS.statSync(Path.join(packpath, p));
			if(fstate.isDirectory()){
				packs.push(p);
			}
		}
    }
    return packs;
}
